package com.bs.resa.service.impl;

import com.bs.resa.common.DatetimeUtils;
import com.bs.resa.common.RedisUtils;
import com.bs.resa.dao.*;
import com.bs.resa.pojo.*;
import com.bs.resa.service.ProjectService;
import com.bs.resa.service.TaskService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author lin
 * @date 2019/3/26 11:50
 */
@Service
public class TaskServiceImpl implements TaskService {
    private static   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    private static   SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
    private Log log=new Log();

    @Resource
    TaskMapper taskMapper;
    @Resource
    ProjectMapper projectMapper;
    @Resource
    RedisUtils redisUtils;
    @Value("${fastdfs_setting.IMAGE_SERVER_URL}")
    private String url;
    @Resource
    FileMapper fileMapper;
    @Resource
    LogMapper logMapper;
    @Resource
    AdminUserMapper adminUserMapper;


    @Override
    public List<Map<String, Object>> queryTaskByPid(String pid,String taskName) {
        //获得项目的任务
        List<Map<String,Object>> taskList=taskMapper.queryTaskList(pid,taskName);
//        System.out.println("任务："+taskList);
        for(Map<String,Object> map:taskList){
            map.put("url",url);
            map.put("endtime",map.get("tEndDate")!=null?df2.format(map.get("tEndDate")):"");
            if(DatetimeUtils.compare_date(map.get("tEndDate").toString(),df.format(new Date()).toString())==-1){
                map.put("style","color:red");
            }else{
                map.put("style","");
            };


        }
        return taskList;
    }

    @Override
    public Boolean insertTaskByPid(Task task, String pid) throws ParseException {
        //新增task表
        //默认状态未开始1
        boolean flag=false;
        AdminUser adminUser=((AdminUser)redisUtils.getObject("userinfo"));
        task.setTaskstatusid((long) 1);
        task.settCreateUserId(adminUser.getId());
        task.setTcreatedate(df.parse(df.format(new Date())));
        task.setTenddate(df.parse(df.format(task.getTenddate())));
       try {

       log.setUserId(adminUser.getId());
       log.setData(df.parse(df.format(new Date())));

        Integer i=taskMapper.insertTask(task);
        if(i==1){
//            System.out.println("新增任务成功");
            if(pid!=null){
                //插入任务编号
                //通过项目id 查询项目任务编号前缀
                Project project=projectMapper.queryById(pid);
                String tNumber=project.getPnumber()+task.getTid();
                taskMapper.updateTaskNumber(tNumber,task.getTid());

                //新增project_task表
                projectMapper.insertProjectTask(pid,task.getTid());
                log.setProjectId(Long.valueOf(pid));
                log.setDesc("用户"+adminUser.getAccount()+"为项目"+project.getPname()+"创建任务："+task.getTitle()+"。" +
                        "负责人："+(adminUserMapper.queryUserById(String.valueOf(task.getTuserid()))).getAccount());
                logMapper.insertLog(log);
                //更新项目状态为进行中2
                projectMapper.updateStatus(pid);
            }
            flag=true;
        }

       }catch (Exception e){
           flag=false;
       }
        return flag;
    }

    /**
     * 获得甘特图数据
     *
     *
     */
    @Override
    public List<Map<String, Object>> queryTaskByPidGantetu(String pid) throws ParseException {
        List<Map<String, Object>> taskList=taskMapper.queryTaskList(pid,null);
        System.out.println("任务："+taskList);
        List<Map<String,Object>> list=new ArrayList<>();

        for(Map<String,Object> taskMap:taskList){
            Map<String,Object> map=new HashMap<>();
            Map<String,Object> series=new HashMap<>();
            List<Map<String,Object>> listSeries=new ArrayList<>();

            map.put("id",taskMap.get("tId"));
            map.put("name",taskMap.get("tNumber"));
            series.put("title",taskMap.get("title"));
            series.put("name", (String)taskMap.get("StatusIcon") + (String)taskMap.get("title"));


            series.put("start",getDate((Date)taskMap.get("tCreateDate")));
            series.put("end", getDate((Date)taskMap.get("tEndDate"))==null?getDate((Date)taskMap.get("tCreateDate")):getDate((Date)taskMap.get("tEndDate")));
            series.put("color",taskMap.get("gantuColor"));
            listSeries.add(series);
            map.put("series",listSeries);

            list.add(map);
        }
        return list;
    }

    /**
     * 获得图的数据
     *
     * @param pid
     * @return
     */
    @Override
    public Map<String, Object> getTuDate(String pid) {
        Map<String,Object> map=new HashMap<>();

        Map<String,Object> tu1=new HashMap<>();
        Map<String,Object> tu2=new HashMap<>();
        List<Map<String,Object>> taskType=taskMapper.queryTaskType();

        //图1
        List<Map<String,Object>> series=new ArrayList<>();
        List<String> legend=new ArrayList<>();
        List<String> color=new ArrayList<>();
        for(Map<String,Object> type:taskType){
            Map<String,Object> maps=new HashMap<>();
            legend.add((String)type.get("tName"));
            color.add((String)type.get("color"));
            //通过tid 和pid获得当前类型的数量统计
            int i= taskMapper.getCountTaskType((Long)type.get("id"),pid);
            //总任务数
            maps.put("value",i);
            maps.put("name",(String)type.get("tName"));
            series.add(maps);
        }

        //组件legend-date
        tu1.put("legend",legend);
        tu1.put("color",color);
        tu1.put("series",series);


        List<Map<String,Object>> listType=taskMapper.queryTaskStatusList();
        //图1
        List<Map<String,Object>> series2=new ArrayList<>();
        List<String> legend2=new ArrayList<>();
        List<String> color2=new ArrayList<>();
        for(Map<String,Object> type:listType){
            Map<String,Object> maps=new HashMap<>();
            legend2.add((String)type.get("ptName"));
            color2.add((String)type.get("tucolor"));
            int i=taskMapper.getCountTaskStatus(pid,(Long)type.get("pTid"));
            maps.put("value",i);
            maps.put("name",type.get("ptName"));
            series2.add(maps);
        }

        //组件legend-date
        tu2.put("legend",legend2);
        tu2.put("color",color2);
        tu2.put("series",series2);

        map.put("tu1",tu1);
        map.put("tu2",tu2);
        return map;
    }

    /**
     * 任务视图-查询我参与
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> queryMytask() {
       List<Map<String, Object>> result=new ArrayList<>();
        //查询三种状态
        Long userid=((AdminUser)redisUtils.getObject("userinfo")).getId();
        List<Map<String,Object>> taskLeibie=taskMapper.queryTaskLeibie();
        for(Map<String,Object> leibie:taskLeibie){
            Map<String,Object> map=new HashMap<>();
            List<Map<String, Object>> TaskMy=taskMapper.queryTaskMy(userid,(Long)leibie.get("id"));
            for(Map<String,Object> map1:TaskMy){
                map1.put("url",url);

                String message="";
                if(map1.get("tEndDate")!=null){

                    if(DatetimeUtils.compare_date(map1.get("tEndDate").toString(),df.format(new Date()).toString())==1){
                        message="<div class=\"stat-icon dib bg-flat-color-5\">截止时间:"+df2.format((Date)map1.get("tEndDate"))+"</div>";
                    } else{
                        message="<div class=\"stat-icon dib bg-flat-color-5\" style=\"color:red\">截止时间:"+df2.format((Date)map1.get("tEndDate"))+"</div>";
                    }

                }
                map1.put("endStart",message);
            }
            map.put(String.valueOf( leibie.get("modelid")),TaskMy);
            result.add(map);
        }
        return result;
    }

    /**
     * 更新任务状态
     *
     * @param tid
     * @param sid
     * @return
     */
    @Override
    public Map<String,Object> updataStatus(String tid, String sid) {

        int i=taskMapper.updataStatus(tid,sid);
        Map<String,Object> task=taskMapper.queryTaskByid(tid);
        task.put("url",url);
        String message="";
        if(task.get("tEndDate")!=null){

            if(DatetimeUtils.compare_date(task.get("tEndDate").toString(),df.format(new Date()).toString())==1){
                message="<div class=\"stat-icon dib bg-flat-color-5\">截止时间:"+df2.format((Date)task.get("tEndDate"))+"</div>";
            } else{
                message="<div class=\"stat-icon dib bg-flat-color-5\" style=\"color:red\">截止时间:"+df2.format((Date)task.get("tEndDate"))+"</div>";
            }

        }
        task.put("endStart",message);
        String pid=taskMapper.getProjectid(tid);
        //判断是否修改项目状态
        if(pid!=null && !pid.equals("")){
            int success=taskMapper.queryTaskByProject3(pid);
            int count=taskMapper.getCountTask(pid);
            if(success==count){
                //更新项目状态
                projectMapper.updateStatusSuccess(pid);
            }else{
                projectMapper.updateStatus(pid);
            }
        }

        if(i!=0){
            return task;
        }
        return task;
    }

    /**
     * 查询任务详细信息
     *
     * @param tid
     * @return
     */
    @Override
    public Map<String, Object> queryTaskByTid(String tid) {
        redisUtils.set("tid",tid);
        SimpleDateFormat dfs=new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> result=new HashMap<>();
        Map<String,Object> taskinfo=taskMapper.queryTaskByid(tid);
        taskinfo.put("startTime",dfs.format(taskinfo.get("tCreateDate")));
        taskinfo.put("endTime",taskinfo.get("tEndDate")==null?null:dfs.format(taskinfo.get("tEndDate")));
        taskinfo.put("url",url);
        String message="";
        if(taskinfo.get("tEndDate")!=null){

            if(DatetimeUtils.compare_date(taskinfo.get("tEndDate").toString(),df.format(new Date()).toString())==-1){
                message="<div class=\"stat-icon dib bg-flat-color-5\">截止时间:"+taskinfo.get("tEndDate")+"</div>";
            } else{
                message="<div class=\"stat-icon dib bg-flat-color-5\" style=\"color:red\">截止时间:"+taskinfo.get("tEndDate")+"</div>";
            }

        }
        taskinfo.put("endStart",message);
        result.put("taskinfo",taskinfo);
        //查询任务附件
//        List<Map<String,Object>> taskFiles=fileMapper.queryTaskId(tid);
//        Map<String,Object> filInfo=new HashMap<>();
//        List<String> initialPreview = null;
//        List<Object> previewConfig = null;
//        Map<String,Object> initialPreviewConfig=null;
//        int i=1;
//        initialPreview=new ArrayList<>();
//        previewConfig=new ArrayList<>();
//        for(Map<String,Object> f:taskFiles){
//            initialPreviewConfig=new HashMap<>();
//            initialPreview.add(String.valueOf(f.get("fPath")));
//
//            initialPreviewConfig.put("caption",String.valueOf(f.get("fTitle")));
//            initialPreviewConfig.put("size",String.valueOf(f.get("size")));
//            initialPreviewConfig.put("width","120px");
//            initialPreviewConfig.put("url","{$url}");
//            initialPreviewConfig.put("key",i);
//            previewConfig.add(initialPreviewConfig);
//            i++;
//        }
//        filInfo.put("initialPreview",initialPreview);
//        filInfo.put("initialPreviewConfig",previewConfig);
//       result.put("taskfile",filInfo);

        result.put("taskfile", fileMapper.queryTaskId(tid));


        return result;
    }

    /**
     * 更新任务信息
     * @param startTime
     * @param endTime
     * @param select 优先级
     * @param editor 描述
     * @return
     */
    @Override
    public boolean updataInfo(String startTime,String endTime,String select,String editor) throws ParseException {
        Task task=new Task();
        task.setTcreatedate(df.parse(df.format(df.parse(startTime+" 00:00:00"))));
        System.out.println("结束时间："+endTime);
        if(endTime!=null&&!endTime.equals("")){
            task.setTenddate(df.parse(df.format(df.parse(endTime+" 00:00:00"))));
        }

        task.setDescription(editor);
        task.setTorderby(select);
        task.setTid(Long.valueOf(redisUtils.get("tid")));
        int i=taskMapper.updataTaskInfo(task);
        if(i!=0){
            return  true;
        }
        return false;
    }

    /**
     * 更新任务类别
     *
     * @param tid
     * @param lei
     * @return
     */
    @Override
    public boolean updataTaskLei(String tid, String lei) {
        int j=taskMapper.updateTaskLei(tid,lei);
        if(j!=0){
            return true;
        }
        return false;
    }

    @Override
    public Long insertMyTask(String descr, String select, String id) throws ParseException {
        Task task=new Task();
        task.setTitle(descr);
        task.setTtypeid(Long.valueOf(select));
        task.setTaskstatusid((long) 1);
        task.settCreateUserId(((AdminUser)redisUtils.getObject("userinfo")).getId());
        task.setTuserid(((AdminUser)redisUtils.getObject("userinfo")).getId());

        task.setTcreatedate(df.parse(df.format(new Date())));
        int leiid=0;
        switch (id){
            case "one": leiid=1;break;
            case "two": leiid=2;break;
            case "three": leiid=3;break;
        }
        int j=taskMapper.insertMyTask(task,leiid);
        if(j!=0){
            taskMapper.updateTaskNumber(String.valueOf(task.getTid()),task.getTid());
        }

        return task.getTid();
    }

    /**
     * 统计任务查询
     *
     * @return
     */
    @Override
    public Map<String, Object> queryMytaskCount() {
        Map<String,Object> resultMap=new HashMap<>();
        AdminUser adminUser=(AdminUser)redisUtils.getObject("userinfo");
        List<Map<String,Object>> maps=taskMapper.queryTaskStatusList();
        for(Map<String,Object> map:maps){
            resultMap.put("map"+String.valueOf(map.get("pTid")),taskMapper.queryTaskStatusCount(adminUser.getId(),(Long)map.get("pTid")));
        }

        return resultMap;
    }

    /**
     * 查询完成的任务
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> querySuccTask(String taskName) {
        Long userid=((AdminUser)redisUtils.getObject("userinfo")).getId();
        List<Map<String,Object>> data=taskMapper.queryTaskMySucc(userid,taskName);
        for(Map<String,Object> map:data){
            map.put("url",url);
            map.put("endtime",map.get("tEndDate")!=null?df2.format(map.get("tEndDate")):"");
        }
        return data;
    }

    public static  String getDate(Date date){
        return df.format(date).substring(0,10);
    }

    public static void main(String[] args) throws ParseException {
        getDate(df.parse(df.format("2019-01-11T16:00:00.000+0000")));
    }
}
